package com.project.les;

import java.io.IOException;
import java.util.List;

import android.app.ListActivity;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.project.les.view.adapters.FeriadoListAdapter;
import com.project.les.view.elements.FeriadoViewElement;

public class LocaisListActivity extends ListActivity {

	private TextView endereco;
	// private MapView mapa;
	// private MyLocationOverlay myLocOverlay;

	private LocationManager locManager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.nacionais);

		// endereco = (TextView) findViewById(R.id.textView1);

		locManager = (LocationManager) getSystemService(LOCATION_SERVICE);

		String[] locate = georeferenciar();
		if(locate == null) {
			//toast("Serviço indisponível ou cidade nao encontrada.");
		}
		else {
			String city = locate[0];
			//String state = locate[1];	
			List<FeriadoViewElement> data = DataHelper.getInstance().selectAll(
					"city LIKE '%" + city + "%'");
			setListAdapter(new FeriadoListAdapter(this, data));
		}

		// Comentado porque a ordenação foi implementada na query do banco de
		// dados:
		// Collections.sort(data, new OrdenaFeriados());
		

		ListView lv = getListView();
		lv.setTextFilterEnabled(true);
	}

	private String[] georeferenciar() {

		Location location = locManager
				.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

		if (location == null) {
			toast("Localização não disponível!");
		} else {
			try {

				double lat = location.getLatitude();
				double lon = location.getLongitude();

				Geocoder geo = new Geocoder(this);

				List<Address> addresses = geo.getFromLocation(lat,
						lon, 1);

				if (addresses != null) {
					
					Address returnedAddress = addresses.get(0);

					String line = returnedAddress.getAddressLine(1);
					//toast(line);
					String[] listLine = line.split("-");

					if (listLine.length == 2) {
						String city = listLine[0].trim();
						String state = listLine[1].trim();
						String [] locate = {city, state};
						return locate;
					} else {
						return null;
					}

				} else {
					return null;
				}

			} catch (Exception e) {
				toast("Verifique a conexão de internet!"); // no simulador irá ocorrer I/O Exception
										// por falta de serviço
			}
		}
		return null;
	}

	public void toast(String message) {
		Toast.makeText(this, message, Toast.LENGTH_LONG).show();
	}

}
